import re

from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django import http
from django.shortcuts import render
from django.conf import settings
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from utils.response_code import RETCODE
from QQLoginTool.QQtool import OAuthQQ

class QQLoginURLView(View):

    def get(self,request):
        next = request.GET.get('next')

        #1.创建OAuthQQ 实例对象
        qq=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                   client_secret=settings.QQ_CLIENT_SECRET,
                   redirect_uri=settings.QQ_REDIRECT_URI,
                   state=next)
        #2.调用指定方法获取指定数据
        login_url = qq.get_qq_url()

        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_url})


class QQAuthUserView(View):
    """用户扫码登录的回调处理"""

    def get(self, request):
        """Oauth2.0认证"""
        # 接收Authorization Code
        code = request.GET.get('code')
        state = request.GET.get('state')
        if code is None:
            return http.HttpResponseBadRequest('缺少code')

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)

        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)

            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)

        except BaseException:
            return http.HttpResponseServerError('OAuth2.0认证失败')

        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:

            # 如果openid没绑定美多商城用户

            return render(request, 'oauth_callback.html',context={'openid':openid})
        else:
            # 如果openid已绑定美多商城用户

            qq_user = oauth_user.user
            login(request, qq_user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)

            return response

    def post(self,request):
        mobile = request.POST.get("mobile")
        pwd = request.POST.get('pwd')
        sms = request.POST.get('sms_code')
        openid = request.POST.get('openid')

        if not all([mobile,pwd,sms,openid]):
            return http.HttpResponseBadRequest("参数不全")

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('请输入正确的手机号码')

        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseBadRequest('请输入8-20位的密码')

        redis_conn = get_redis_connection('code')
        sms_code = redis_conn.get('sms_%s'%mobile)
        if sms_code is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的短信验证码'})

        if sms != sms_code.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})

        # 判断用户绑定没有绑定过
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 用户不存在,新建用户
            user = User.objects.create_user(username=mobile,
                                            password=pwd,
                                            mobile=mobile)
        else:
            # 如果用户存在，检查用户密码
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})


        qquser = OAuthQQUser.objects.create(openid=openid, user=user)
            # 实现状态保持
        login(request, user)

        # 响应绑定结果
        next = request.GET.get('state')
        response = redirect(reverse("contents:index"))

        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        return response